package tools

import (
	"encoding/gob"

	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/sessions"
)

//session启动和配置

// 声明 store 变量
var store *sessions.CookieStore

func init() {
	store = sessions.NewCookieStore([]byte("recomend-32bytes-secret"))

	store.Options = &sessions.Options{
		//需要配置生命周期还有cookie相关的内容

		Path:     "/",
		MaxAge:   0, //浏览器关闭自动失效(针对cookie
		Domain:   "",
		Secure:   false,
		SameSite: http.SameSiteLaxMode,
	}

	//细节:session存储复杂数据(结构对象)  需要先进行注册
	gob.Register(users.Users{})

}

//session的设置和获取

func SetSession(ctx *gin.Context, key string, value interface{}) error {
	session, err := store.Get(ctx.Request, "SHOPID")

	if err != nil {
		return err
	}

	//存储数据
	session.Values[key] = value
	//保存session 到文件,同时返回可能出现的错误
	return session.Save(ctx.Request, ctx.Writer)
}

func GetSession(ctx *gin.Context, key string) interface{} {
	session, err := store.Get(ctx.Request, "SHOPID")

	if err != nil {
		return err
	}

	//返回取出的结果

	return session.Values[key]
}
